package com.jbit.hxy.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.jbit.hxy.common.Result;
import com.jbit.hxy.properties.AliYunSmsProperties;
import com.jbit.hxy.service.user.SmsService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.io.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {


    private final AliYunSmsProperties aliYunSmsProperties;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信验证码
     *
     * @param phoneNumber 接收短信的手机号码
     * @return
     */
    @Override
    public Result sendSms(String phoneNumber) throws ExecutionException, InterruptedException {
        // 配置证书认证信息，包括ak、secret
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliYunSmsProperties.getAccessKeyId())
                .accessKeySecret(aliYunSmsProperties.getAccessKeySecret())
                .build());
        // 配置AsyncClient客户端
        AsyncClient client = AsyncClient.builder()
                .region(aliYunSmsProperties.getRegionId()) // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(aliYunSmsProperties.getEndpoint())
                        .setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // 随机生成4位整数，作为短信验证码
        int code = RandomUtil.randomInt(1000, 9999);
        // 将验证码存入Redis，设置过期时间为5分钟
        ValueOperations<String, String> vo = stringRedisTemplate.opsForValue();
        if(vo.get(phoneNumber) != null){
            return Result.fail("获取验证码操作太频繁，请稍后再试");
        }
        else {
            stringRedisTemplate.opsForValue().set(phoneNumber, String.valueOf(code), 5, TimeUnit.MINUTES);
        }

        // API请求的参数设置
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(aliYunSmsProperties.getSignName())
                .templateCode(aliYunSmsProperties.getTemplateCode())
                .phoneNumbers(phoneNumber)
                .templateParam("{\"code\":\""+code+"\"}")
                .build();


        // 异步获取API请求的返回值
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 同步获取API请求的返回值
        SendSmsResponse resp = response.get();
        //关闭客户端
        client.close();

        if("OK".equals(resp.getBody().getCode()) && "OK".equals(resp.getBody().getMessage())){
            return Result.success("验证码已发送成功");
        }
        return Result.fail("验证码发送失败,请稍后再试");
    }
}
